import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
//创建axios对象
 const request=axios.create({
    baseURL: '/api',
    timeout: 600000
 });

 //axios的请求request拦截器
 request.interceptors.request.use(
    (config)=>{
        const loginUser=JSON.parse(localStorage.getItem("loginUser"));
        const Student=JSON.parse(localStorage.getItem("Student"));
        if(loginUser && loginUser.token){
            config.headers.token =loginUser.token;   
        }else if( Student && Student.token){
            config.headers.token =Student.token;
        }
        return config;
    },
 );

 //axios的响应response拦截器
 request.interceptors.response.use(
    (response)=>{ 
        return response.data;
    },
    (error)=>{
        if(error.response.status===401){
            router.push("/");
        }else{
            ElMessage.error('访问异常');
        }
        return Promise.reject(error);
    }
);

//导出request
export default request;